<script>
import { batchDelete, page } from '@/api/activationCodeUsage';
import { FilterMatchMode } from '@primevue/core/api';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import { useToast } from 'primevue/usetoast';
import Dropdown from 'primevue/dropdown';
import TreeSelect from 'primevue/treeselect';
import { listQuestionBank } from '@/api/questionBank';
import { useRouter } from 'vue-router';

export default {
    components: {
        InputText,
        Button,
        Dropdown,
        TreeSelect
    },
    data() {
        return {
            activationCodes: [],
            activationCode: {
                id: null,
                code: '',
                questionBankId: null,
                questionBankName: '',
                status: 1,
                createTime: null,
                updateTime: null
            },
            statuses: [
                { label: '无效', value: 2 },
                { label: '已使用', value: 1 },
                { label: '未使用', value: 0 }
            ],
            selectedActivationCodeUsages: null,
            deleteActivationCodeUsageDialog: false,
            deleteActivationCodeUsagesDialog: false,
            loading: false,
            filters: {
                global: { value: null, matchMode: FilterMatchMode.CONTAINS }
            },
            pageSize: 10,
            pageNum: 1,
            totalRecords: 0,
            searchQuery: {
                userId: null,
                questionBankId: null,
                status: null,
                activationCodeId: null
            },
            selectedQuestionBank: null,
            questionBanks: []
        };
    },
    mounted() {
        this.loadActivationCodeUsages();
        this.loadQuestionBanks();
    },
    methods: {

        async loadActivationCodeUsages() {
            this.loading = true;
            try {
                const params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    ...this.searchQuery
                };

                const response = await page(params);

                if (response.code === 200) {
                    this.activationCodes = response.data.list || [];
                    this.totalRecords = response.data.total || 0;
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载激活码使用记录数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载激活码使用记录数据',
                    life: 3000
                });
                console.error('加载激活码使用记录失败:', error);
            } finally {
                this.loading = false;
            }
        },

        async loadQuestionBanks() {
            try {
                const response = await listQuestionBank({
                    pageNum: 1,
                    pageSize: 1000,
                    language: null
                });

                if (response.code === 200) {
                    this.questionBanks = (response.data || []).map((item) => ({
                        key: item.id.toString(),
                        label: item.name,
                        data: item.id
                    }));
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载题库数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载题库数据',
                    life: 3000
                });
                console.error('加载题库失败:', error);
            }
        },

        resetSearch() {
            this.searchQuery = {
                code: null,
                questionBankIds: null,
                status: null,
                createTimeRange: null
            };
            this.selectedQuestionBank = null;
            this.loadActivationCodeUsages();
        },

        onPage(event) {
            this.pageNum = event.page + 1;
            this.pageSize = event.rows;
            this.loadActivationCodeUsages();
        },
        onSort(event) {
            let sortField = event.sortField;
            let sortOrder = event.sortOrder;
            if (sortField) {
                this.activationCodes.sort((a, b) => {
                    let result = 0;
                    if (a[sortField] < b[sortField]) {
                        result = -1;
                    } else if (a[sortField] > b[sortField]) {
                        result = 1;
                    }
                    return sortOrder === 1 ? result : -result;
                });
            }
        },

        performSearch() {
            this.pageNum = 1;
            this.loadActivationCodeUsages();
        },

        handleQuestionBankChange(value) {
            if (value && typeof value === 'object') {
                const keys = Object.keys(value);
                if (keys.length > 0) {
                    this.searchQuery.questionBankId = parseInt(keys[0]);
                } else {
                    this.searchQuery.questionBankId = null;
                }
            } else {
                this.searchQuery.questionBankId = value;
            }
        },

        confirmDeleteActivationCodeUsage(activationCode) {
            this.activationCode = activationCode;
            this.deleteActivationCodeUsageDialog = true;
        },

        async deleteActivationCodeUsage() {
            try {
                this.loading = true;
                const response = await batchDelete([this.activationCode.id]);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '激活码使用记录已删除',
                        life: 3000
                    });
                    this.deleteActivationCodeUsageDialog = false;
                    this.loadActivationCodeUsages();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '删除激活码使用记录失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '删除激活码使用记录时出错',
                    life: 3000
                });
                console.error('删除激活码使用记录失败:', error);
            } finally {
                this.loading = false;
                this.deleteActivationCodeUsageDialog = false;
            }
        },

        confirmDeleteSelected() {
            this.deleteActivationCodeUsagesDialog = true;
        },

        async deleteSelectedActivationCodeUsages() {
            try {
                this.loading = true;
                const ids = this.selectedActivationCodeUsages.map((ac) => ac.id);
                const response = await batchDelete(ids);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '选中的激活码使用记录已删除',
                        life: 3000
                    });
                    this.selectedActivationCodeUsages = null;
                    this.deleteActivationCodeUsagesDialog = false;
                    this.loadActivationCodeUsages();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '批量删除激活码使用记录失败',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '批量删除激活码使用记录时出错',
                    life: 3000
                });
                console.error('批量删除激活码使用记录失败:', error);
            } finally {
                this.loading = false;
                this.deleteActivationCodeUsagesDialog = false;
            }
        },

        exportCSV() {
            this.$refs.dt.exportCSV();
        }
    },
    setup() {
        const toast = useToast();
        const router = useRouter();
        return { toast, router };
    }
};
</script>

<template>
    <div>
        <div class="card">
            <Toast />
            <Toolbar class="mb-6">
                <template #start>
                    <Button label="批量删除" icon="pi pi-trash" severity="secondary" @click="confirmDeleteSelected" :disabled="!selectedActivationCodeUsages || !selectedActivationCodeUsages.length" />
                </template>
                <template #end>
                    <Button label="生成激活码使用记录" icon="pi pi-plus" severity="primary" class="mr-2" @click="goToGeneratePage" />
                    <Button label="导出" icon="pi pi-upload" severity="secondary" @click="exportCSV($event)" />
                </template>
            </Toolbar>
            <Toolbar>
                <template #start>
                    <div class="flex flex-wrap items-center gap-2">
                        <InputText v-model="searchQuery.userId" placeholder="搜索用户ID" class="mr-2" />
                        <InputText v-model="searchQuery.activationCodeId" placeholder="搜索激活码ID" class="mr-2" />
                        <TreeSelect v-model="selectedQuestionBank" :options="questionBanks" selectionMode="single" placeholder="选择题库" class="mr-2 w-12rem" :filter="true" :showClear="true" @update:modelValue="handleQuestionBankChange" />
                        <Button v-if="Object.values(searchQuery).some((value) => value !== null && value !== '')" label="重置" icon="pi pi-eraser" severity="info" @click="resetSearch" color="mr-2" />
                    </div>
                </template>
                <template #end>
                    <Button label="搜索" icon="pi pi-search" @click="performSearch" />
                </template>
            </Toolbar>
            <DataTable
                ref="dt"
                v-model:selection="selectedActivationCodeUsages"
                :value="activationCodes"
                dataKey="id"
                :paginator="true"
                :rows="pageSize"
                lazy
                :totalRecords="totalRecords"
                scrollable
                :loading="loading"
                @page="onPage($event)"
                @sort="onSort($event)"
                :filters="filters"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 20, 50]"
                currentPageReportTemplate="显示 {first} 到 {last} 共 {totalRecords} 条记录"
            >
                <template #header>
                    <h4 class="m-0">激活码使用记录管理</h4>
                </template>

                <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
                <Column field="id" frozen header="ID" sortable style="min-width: 5rem" bodyClass="text-center"></Column>
                <Column field="userId" frozen header="用户ID" sortable style="min-width: 5rem" bodyClass="text-center"></Column>
                <Column field="username" frozen header="用户名" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="questionBankName" header="所属题库" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column field="activationCodeId" header="激活码ID" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column frozen alignFrozen="right" header="操作" style="min-width: 10rem" bodyClass="text-center">
                    <template #body="slotProps">
                        <Button icon="pi pi-trash" outlined rounded severity="danger" @click="confirmDeleteActivationCodeUsage(slotProps.data)" />
                    </template>
                </Column>
            </DataTable>
        </div>

        <!-- 删除确认对话框 -->
        <Dialog v-model:visible="deleteActivationCodeUsageDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span v-if="activationCode"
                    >确定要删除激活码使用记录 <b>{{ activationCode.code }}</b> 吗？</span
                >
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteActivationCodeUsageDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteActivationCodeUsage" />
            </template>
        </Dialog>

        <!-- 批量删除确认对话框 -->
        <Dialog v-model:visible="deleteActivationCodeUsagesDialog" :style="{ width: '450px' }" header="确认删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span>确定要删除选中的激活码使用记录吗？</span>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteActivationCodeUsagesDialog = false" />
                <Button label="确定" icon="pi pi-check" severity="danger" @click="deleteSelectedActivationCodeUsages" />
            </template>
        </Dialog>
    </div>
</template>
